package com.zzh.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.alibaba.fastjson.JSONObject;
import com.angel.MicroSoftOffice.Example2;
import com.angel.acv.pojo.ACv;
import com.angel.base.fileupload.FilePojo;
import com.angel.icv.mapper.ICvMapper;
import com.angel.icv.pojo.ICv;
import com.angel.icv.pojo.ICvExample;
import com.angel.oss.FileOperation;

/**
 * Servlet implementation class MyServlet
 */
@WebServlet("/")
public class DispatcherServlet extends HttpServlet {

	// 初始化持久层
	static SqlSessionFactory ssf = null;
	static SqlSession ss = null;
	static ICvMapper iCvMapper;
	Map<String, String> map = new HashMap<String, String>();
	static String dir = "d:/tmp";

	static {
		try {
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			ssf = new SqlSessionFactoryBuilder().build(inputStream);
			ss = ssf.openSession();
			iCvMapper = ss.getMapper(ICvMapper.class);

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		try {
			map.put("msg", "False");
			response.setContentType("application/json;charset=UTF-8");

			System.out.println("name: " + request.getParameter("name"));
			System.out.println("id: " + request.getParameter("id"));

			// 获取简历id
			String uid = request.getParameter("id");

			// 查询数据库获取原始简历的oss存储路径
			ICvExample iCvExample = new ICvExample();
			iCvExample.createCriteria().andUidEqualTo(uid);
			List<ICv> cvs = iCvMapper.selectByExample(iCvExample);
			if (cvs.size() > 0) {
				ICv cv = cvs.get(0);
				String filepath = cv.getFilepath();
				System.out.println(filepath);
				FilePojo filepojo = JSONObject.parseObject(filepath, FilePojo.class);
				System.out.println(filepojo.getOssPath());
				// response.getWriter().append(filepath);
				// 获取oss文件流
				String key = filepojo.getOssPath();
				// String pdfpath = filepojo.getPdfPath();
				if (key != null) {
					String filename = key.substring(key.lastIndexOf("/")); // xxx.doc
					String des = dir + File.separator + filename;
					File file = FileOperation.DownLoadFile(key, des);

					// 转换word为pdf
					String sfileName = des;
					String toFileName = dir + File.separator + filename.substring(0, filename.lastIndexOf("."))
							+ ".pdf";
					Example2.wordToPDF(sfileName, toFileName);
					// 上传pdf到oss
					key = key.substring(0, key.lastIndexOf(".")) + ".pdf";
					FileOperation.UpLoadFile(toFileName, key);
					// 如果上传成功，清空文件

					File sfile = new File(sfileName);
					if (sfile.exists())
						sfile.delete();

					File tofile = new File(toFileName);
					if (tofile.exists())
						tofile.delete();

					// 更新数据库pdfPath
					// ICv cv2 = new ICv();
					// filepojo.setPdfPath(key);
					// cv2.setFilepath(JSONObject.toJSONString(filepojo));
					// iCvMapper.updateByExampleSelective(cv2, iCvExample);
					// ss.commit();
					map.put("msg", "Success");
				} else {
					map.put("msg", "Not Found");
				}

			}
			// 结果返回：状态、路径
			response.getWriter().append(JSONObject.toJSONString(map));
		} catch (Exception e) {
			ss.rollback();
			e.printStackTrace();
		}

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		map.put("msg", "False");
		try {
			response.setContentType("application/json;charset=UTF-8");

			System.out.println("oldPath: " + request.getParameter("oldPath"));

			// 获取简历id
			String oldPath = request.getParameter("oldPath");
			// cv/130/17072522161956771718/17072522161956771718.doc
			// 查询数据库获取原始简历的oss存储路径
			String filepath = oldPath;
			// response.getWriter().append(filepath);
			// 获取oss文件流
			String key = oldPath;
			// String pdfpath = filepojo.getPdfPath();
			if (key != null) {
				String filename = key.substring(key.lastIndexOf("/")); // xxx.doc
				String des = dir + File.separator + filename;
				File file = FileOperation.DownLoadFile(key, des);

				// 转换word为pdf
				String sfileName = des;
				String toFileName = dir + File.separator + filename.substring(0, filename.lastIndexOf(".")) + ".pdf";
				Example2.wordToPDF(sfileName, toFileName);
				// 上传pdf到oss
				key = key.substring(0, key.lastIndexOf(".")) + ".pdf";
				FileOperation.UpLoadFile(toFileName, key);
				// 如果上传成功，清空文件

				File sfile = new File(sfileName);
				if (sfile.exists())
					sfile.delete();

				File tofile = new File(toFileName);
				if (tofile.exists())
					tofile.delete();

				map.put("msg", "Success");
			} else {
				map.put("msg", "Not Found");
			}
		} catch (Exception e) {
			ss.rollback();
			e.printStackTrace();
		}
		// 结果返回：状态、路径
		response.getWriter().append(JSONObject.toJSONString(map));

	}
}
